<template>
  <view class="chat">
    <scroll-view scroll-y class="chat-box" :scroll-top="scrollTop" scroll-with-animation>
      <view v-for="(msg, index) in messages" :key="index" :class="['msg', msg.role]">
        <text class="time">{{ msg.time }}</text>
        <view class="bubble">{{ msg.content }}</view>
      </view>
      <view style="height: 20px" />
    </scroll-view>

    <view class="input-area">
      <input
        v-model="inputText"
        class="input"
        placeholder="请输入内容..."
        confirm-type="send"
        @confirm="sendMessage"
      />
      <button class="send" @click="sendMessage" :loading="loading">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'

const messages = ref<{ role: string; content: string; time: string }[]>([])
const inputText = ref('')
const loading = ref(false)
const scrollTop = ref(0)

const formatTime = () => {
  const d = new Date()
  return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`
}

const scrollToBottom = () => {
  scrollTop.value = 99999
}

const sendMessage = async () => {
  const text = inputText.value.trim()
  if (!text || loading.value) return

  messages.value.push({ role: 'user', content: text, time: formatTime() })
  inputText.value = ''
  loading.value = true
  nextTick(() => scrollToBottom())

  try {
    const result = await uni.request({
      url: 'https://xrqr0h0x1w.gzg.sealos.run/get_smallxhy', // 你的 Laf 云函数地址
      method: 'POST',
      header: { 'Content-Type': 'application/json' },
      data: { message: text }
    })

    const reply = result.data?.data || '无回复'
    messages.value.push({ role: 'assistant', content: reply, time: formatTime() })
    nextTick(() => scrollToBottom())
  } catch (err) {
    console.error('请求失败:', err)
    uni.showToast({ title: '请求失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.chat {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.chat-box {
  flex: 1;
  padding: 20rpx;
  background: #f7f7f7;
  overflow: auto;
}
.msg {
  margin-bottom: 20rpx;
}
.msg .time {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}
.msg.user {
  align-items: flex-end;
  text-align: right;
   margin-right: 40rpx;
}
.msg.assistant {
  align-items: flex-start;
  text-align: left;
 
}
.bubble {
  display: inline-block;
  padding: 16rpx 24rpx;
  background-color: #fff;
  border-radius: 12rpx;
  max-width: 80%;
  word-break: break-word;
}
.msg.user .bubble {
  background-color: #a0d911;
  color: #fff;
}
.input-area {
  display: flex;
  padding: 16rpx;
  border-top: 1rpx solid #eee;
  background: #fff;
}
.input {
  flex: 1;
  padding: 16rpx;
  border: 1rpx solid #ccc;
  border-radius: 8rpx;
}
.send {
  margin-left: 16rpx;
  background-color: #4fc08d;
  color: #fff;
  padding: 0 20rpx;
  border: none;
  border-radius: 8rpx;
}
</style>
